<template>
    <div>
        <!-- 导航头部 -->
        <div class="ls-User__centent ls-card m-t-16">
            <el-form label-width="120px" size="small" ref="formRef" :model="form" :rules="formRules">
                <el-form-item label="视频标题:" prop="title" required>
                    <el-input v-model="form.title" :disabled="disabled" />
                </el-form-item>
                <el-form-item label="视频背景图:" prop="poster" required>
                    <material-select :limit="1" v-model="form.poster" :disabled="disabled" />
                    <div class="flex">
                        <div class="muted xs m-r-16">建议尺寸：100*100像素，jpg，jpeg，png图片类型</div>
                    </div>
                </el-form-item>
                <el-form-item label="视频上传" prop="video_path" required>
                    <input type="file"  @change="onVideoChange" accept="video/*" />
                    <div>{{ form.video_path }}</div>
                </el-form-item>
                <el-form-item label="视频时长:" prop="title" required>
                    <el-input type="number" v-model="form.duration" :disabled="disabled" />
                    <div>根据视频长度填写视频时长(秒)</div>
                </el-form-item>
                <!-- <el-form-item label="红包金额:" prop="balance" required>
                    <el-input v-model="form.balance"  :disabled="disabled" />
                </el-form-item> -->


                <el-form-item label="上架状态:" required>
                    <el-radio :label="1" v-model="form.status" :disabled="disabled">上架</el-radio>
                    <el-radio :label="2" v-model="form.status" :disabled="disabled">下架</el-radio>
                </el-form-item>
               
                <el-form-item label="视频介绍:" prop="describe" required class="form-edit">
                    <editor v-model="form.describe" width="375" height="300" />
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script lang="ts">
import {
    Component,
    Prop,
    Ref,
    Vue,
    Watch
} from 'vue-property-decorator'
import { State } from 'vuex-class'

import {
    apiAddVideo,
    apiEditVideo
} from '@/api/application/red_envelope_video'
import Editor from '@/components/editor.vue'
import MaterialSelect from '@/components/material-select/index.vue'
import { IRedEnvelopeVideoEditFormInfo } from '@/interface/red_envelope_video.d'
import Qiniu, { removeSuffix } from '@/utils/QiniuUpload'
import { PageMode } from '@/utils/type'

import { static_red_envelope_video } from './const'

@Component({
    components: {
        MaterialSelect,
        Editor,
    }
})

export default class VideoDetail extends Vue {
    @Ref() readonly formRef!: Element
    @Prop({ default: PageMode.ADD }) mode!: string
    @Prop({ default: false }) visible?: boolean
    @Prop({
        default() {
            return {}
        }
    })
    editInfo!: IRedEnvelopeVideoEditFormInfo | null
    myQiniu = Qiniu
    form: IRedEnvelopeVideoEditFormInfo = {
        ...static_red_envelope_video
    }
    formRules = {
        title: [
            {
                required: true,
                message: '请填写标题',
                trigger: 'blur'
            }
        ],
        
        poster: [
            {
                required: true,
                message: '请上传视频背景图',
                trigger: 'blur'
            }
        ],
       
        video_path:[
            {
                required: true,
                message: '请上传视频',
                trigger: 'blur'
            }
        ],
        balance: [
            {
                required: true,
                message: '请填写红包金额',
                trigger: 'blur'
            }
        ],
        status: [
            {
                required: true,
                message: '',
                trigger: 'blur'
            }
        ],
        introduction: [
            {
                required: true,
                message: '请填写视频介绍',
                trigger: 'blur'
            }
        ]
    }
    disabled = false //是否禁用 查看详情时禁用
    @Watch('mode')
    changeMode(v:string) {
        this.initFormInfo()
    }
    @Watch('visible')
    visibleChange(v:boolean) {
        this.initFormInfo()
    }
    mounted() {
        this.initFormInfo()
    }
    initFormInfo() {
        const formInfo = this.editInfo || this.form
        if (this.mode === PageMode.ADD) {
            this.form = {
                ...static_red_envelope_video
            }
            return
        }
        this.$nextTick(() => {
            this.form = Object.assign({}, formInfo)
        })
       
    }
    
    
    onVideoChange(e: any) {
        const vm = this
        let files = e.target.files;
        let videoFiles:any = [];
        for (let i = 0; i < files.length; i++) {
            const name = removeSuffix(files[i].name, '.mp4')
            videoFiles[i] = {
                title: name,
                path: '',
                status: "等待上传",
                file: files[i]
            };
        }
        this.getDurtion(videoFiles[0]).then((res:any) => {
            vm.form.duration = res.duration
        })
        vm.form.video_path = ''
        this.myQiniu.upload(videoFiles).then((res:any) =>{
            vm.form.video_path = res[0].video_path
        }).catch((err:any )=> {
            //    no catch
        })
    }
    getDurtion(options:any) {
        return new Promise((resolve, reject) => {
            const { file } = options;
            const formData = new FormData();
            formData.append("file", file);
            formData.append("type", "video");
        
            // 创建一个 Video 元素
            const video = document.createElement('video');
            video.preload = 'metadata';
            // 设置 video 的 src 属性为文件的 URL
            // new Blob(file, { type: 'text/plain' });
            video.src = URL.createObjectURL(file);
            // 绑定 loadedmetadata 事件，确保获取到元数据
            video.addEventListener('loadedmetadata', async () => {
                // 获取视频时长
                try {
                    const duration = video.duration;
                    console.log("duration", duration)
                    // 关闭 video 元素
                    video.pause();
                    video.src = '';
                    video.load();
                    resolve({duration});
                } catch (error) {
                    reject(error)
                }
            });
            // 触发加载元数据
            video.load();
        });
    }
    changes(e: any) {}
    
    // 添加
    $refs!: {
        formRef: any
    }
    // 提交
    onSubmit() {
        this.$refs.formRef.validate((valid: boolean): any => {
            if (!valid) {
                return
            }

            // 请求发送
            switch (this.mode) {
                case PageMode.ADD:
                    // 添加
                    return this.addHandler()
                case PageMode.EDIT:
                // 编辑
                return this.editHandler()
            }
        })
    }
    // 添加视频
    addHandler() {
        // 传参
        const vm = this
        const config = JSON.parse(JSON.stringify(this.form))
        Object.assign(config, {
            duration: Number(config.duration)
        })
        delete config.id
        apiAddVideo(config)
            .then(res => {
                vm.successHandler()
            })
            .catch((err: Error) => {})
    }
    // 编辑视频
    editHandler() {
        const vm = this
        const config = JSON.parse(JSON.stringify(this.form))
        Object.assign(config, {
            duration: Number(config.duration)
        })
        apiEditVideo(config).then(() => {
           vm.successHandler()
        }).catch((err: Error) => {

        })
    }
    successHandler() {
        this.$emit("success")
    }
}
</script>
<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
../../../utils/videoUpload../../../utils/videoUpload